package com.mall.search.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mall.search.common.domain.SkuEsModel;
import com.mall.search.server.service.EsSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class EsSaveServiceImpl implements EsSaveService {

    @Autowired
    private RestHighLevelClient client;


    /**
     * 将上架的sku信息保存到es中
     *
     * @param
     * @return
     */
    @Override
    public boolean saveSkuByPublish(String json){
        List<SkuEsModel> skuEsModelList = JSONArray.parseArray(json, SkuEsModel.class);

        BulkRequest bulkRequest = new BulkRequest();

        skuEsModelList.stream().forEach(skuEsModel -> {

            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("product");
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel),XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        BulkResponse bulk= null;
        try {
           bulk=  client.bulk(bulkRequest,RequestOptions.DEFAULT);
        }catch (IOException e){
            throw new RuntimeException(e);
        }


        return bulk.hasFailures();
    }
}
